package com.example.excelimport.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Component
@ConfigurationProperties(prefix = "file")
@Data
public class FilePathConfig {

    /**
     * 获取临时文件目录
     */
    public String getTempDir() {
        return System.getProperty("java.io.tmpdir");
    }

    /**
     * 获取临时文件路径
     */
    public String getTempFilePath(String fileName) {
        // 清理文件名中的非法字符
        String safeFileName = fileName.replaceAll("[^a-zA-Z0-9._-]", "_");
        return Paths.get(getTempDir(), safeFileName).toString();
    }

    /**
     * 确保临时目录存在
     */
    public void ensureTempDirExists() {
        try {
            Path tempDir = Paths.get(getTempDir());
            if (!Files.exists(tempDir)) {
                Files.createDirectories(tempDir);
            }
        } catch (IOException e) {
            throw new RuntimeException("创建临时目录失败", e);
        }
    }
}
